import os, sqlite3

SETTING_DB_PATH = 'settings.db'
DUMMY_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'

LOG_ON = True
PRINT_DEBUG = True

class DBStore(object):
    def _check_db_file(self):
        return os.path.exists(self._db_path)
    
    def _create_or_open_db(self):
        need_create = not self._check_db_file()
        try:
            self._db_conn= sqlite3.connect(self._db_path)
            if need_create:
                c = self._db_conn.cursor()
                c.execute('CREATE TABLE setting(key text, value text)')
                self._db_conn.commit()
        except:
            self._db_conn = None
            pass
    
    def get(self, key, default=None):
        try:
            c = self._db_conn .cursor()
            c.execute("SELECT value FROM setting WHERE key = '%s'" % key)
            values = c.fetchone()
            if values is None:
                return default
            return values[0]
        except:
            return default
        
    def set(self, key, val):
        try:
            c = self._db_conn.cursor()
            old_val = self[key]
            if old_val is None:
                sql = "INSERT INTO setting VALUES ('%s', '%s')" % (key, val)
            elif old_val != val:
                sql = "UPDATE setting SET value = '%s' WHERE key = '%s'" % (val, key)
            else:
                return
            c.execute(sql)
            self._db_conn.commit()
        except:
            pass
    
    def __init__(self, db_path=SETTING_DB_PATH):
        self._db_path = db_path
        self._create_or_open_db()
        
    def __getitem__(self, key):
        return self.get(key)

    def __setitem__(self, key, val):
        self.set(key, val)

